package com.emp.test.springboottest.domain.dao;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.alibaba.fastjson.JSON;
import com.yhd.object.product.PmStock;

@Repository(value = "pmStockDao")
public class PmStockDao {
	
	final static Logger logger = LoggerFactory.getLogger(PmStockDao.class);
	
	@Autowired
	NamedParameterJdbcTemplate namedParameterJdbcTemplate;
	
	public PmStockDao() {
		super();
	}

	@Transactional
	public int[] batchInsert(List<PmStock> pmStocks, String ownerId){
		if(null == pmStocks) return null;
		Assert.hasText(ownerId,"用户不能为空");

		SqlParameterSource[] batch = SqlParameterSourceUtils.createBatch(pmStocks.toArray());
        int[] updateCounts = namedParameterJdbcTemplate.batchUpdate(
                "REPLACE into yhd_pm_stock(productId,warehouseId,vs,uptime,ownerId) values(:productId, :warehouseId, :vs, '"+ DateFormatUtils.ISO_DATETIME_FORMAT.format(new Date()) + "', '" + ownerId + "' )",
                batch);
        
        String[] infomsg = {"异常","新增","更新"};
        for(int i = 0; i < updateCounts.length; i++){
        	if(updateCounts[i] > 2 || 0 == updateCounts[i]){
        		logger.error(infomsg[updateCounts[i]] + JSON.toJSONString(pmStocks.get(i)));
        	}else{
        		logger.info(infomsg[updateCounts[i]]);
        	}
        }
        
        return updateCounts;
	}
	
	@Transactional
	public void insert(PmStock PmStock){
		
	}
	
}
